package cuiyt.datastructure.set;

import cuiyt.datastructure.list.CyList;

/**
 * @author cyt
 * @create 2021-01-12 下午 10:34
 */
public class ListSet<E> implements Set<E> {
    private CyList<E> list = new CyList<>();
    private static int ELEMENT_NOT_FOUND = -1;

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean contains(E element) {
        return list.contain(element);
    }


    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void add(E element) {
        int indexOf = list.indexOf(element);
        if (indexOf != ELEMENT_NOT_FOUND) {
            list.set(indexOf, element);
        } else {
            list.add(element);
        }
    }

    @Override
    public void remove(E element) {
        int index = list.indexOf(element);
        if (index != ELEMENT_NOT_FOUND) {
            list.remove(index);
        }
    }

    @Override
    public void traversal(Visitor visitor) {
        if (visitor == null) return;

        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (visitor.visit(list.get(i))) return;
        }
    }
}
